// chat.js - 聊天室相关功能

// DOM元素
let chatMessages;
let messageInput;
let sendMessageBtn;
let sendFileBtn;
let fileInput;
let usersList;
let roomsList;
let currentChatTitle;
let chatStatus;
let createRoomBtn;
let createRoomModal;
let createRoomForm;
let joinRoomModal;
let joinRoomForm;
let roomError;
let currentRoomForJoin = null;

// 全局变量
let socket;
let currentRoom = 'public';
let currentPrivateChat = null;
let onlineUsers = [];
let isConnected = false;
let chatElementsInitialized = false;

// 初始化DOM元素
function initChatElements() {
  console.log('初始化聊天DOM元素');

  // 只有在聊天页面可见时才初始化元素
  const chatPage = document.getElementById('chat-page');
  if (chatPage && chatPage.classList.contains('d-none')) {
    console.log('聊天页面不可见，暂不初始化DOM元素');
    return false;
  }

  chatMessages = document.getElementById('chat-messages');
  messageInput = document.getElementById('message-input');
  sendMessageBtn = document.getElementById('send-message-btn');
  sendFileBtn = document.getElementById('send-file-btn');
  fileInput = document.getElementById('file-input');
  usersList = document.getElementById('users-list');
  roomsList = document.getElementById('rooms-list');
  currentChatTitle = document.getElementById('current-chat-title');
  chatStatus = document.getElementById('chat-status');
  createRoomBtn = document.getElementById('create-room-btn');
  roomError = document.getElementById('room-error');

  // 初始化创建房间模态框
  const createRoomModalElement = document.getElementById('create-room-modal');
  if (createRoomModalElement) {
    createRoomModal = new bootstrap.Modal(createRoomModalElement);
    createRoomForm = document.getElementById('create-room-form');
  }

  // 初始化加入房间模态框
  const joinRoomModalElement = document.getElementById('join-room-modal');
  if (joinRoomModalElement) {
    joinRoomModal = new bootstrap.Modal(joinRoomModalElement);
    joinRoomForm = document.getElementById('join-room-form');
  }

  // 检查关键元素是否存在
  let allElementsFound = true;

  if (!chatMessages) {
    console.error('找不到聊天消息区域元素');
    allElementsFound = false;
  }

  if (!messageInput) {
    console.error('找不到消息输入框元素');
    allElementsFound = false;
  }

  if (!sendMessageBtn) {
    console.error('找不到发送消息按钮元素');
    allElementsFound = false;
  }

  if (!sendFileBtn) {
    console.error('找不到发送文件按钮元素');
    allElementsFound = false;
  }

  if (!fileInput) {
    console.error('找不到文件输入元素');
    allElementsFound = false;
  }

  if (!usersList) {
    console.error('找不到用户列表元素');
    allElementsFound = false;
  }

  if (!roomsList) {
    console.error('找不到房间列表元素');
    allElementsFound = false;
  }

  if (!currentChatTitle) {
    console.error('找不到当前聊天标题元素');
    allElementsFound = false;
  }

  if (!chatStatus) {
    console.error('找不到聊天状态元素');
    allElementsFound = false;
  }

  chatElementsInitialized = allElementsFound;
  return allElementsFound;
}

// 初始化Socket.IO连接
function initializeSocket() {
  console.log('初始化Socket连接');

  if (!window.Auth || !window.Auth.isLoggedIn || !window.Auth.isLoggedIn()) {
    console.log('用户未登录，无法连接到聊天服务器');
    if (chatMessages) {
      window.Utils.safeSetInnerHTML(chatMessages, '<div class="alert alert-warning">请先登录后使用聊天功能</div>');
    }
    return;
  }

  if (socket) {
    // 已经初始化过
    console.log('Socket已初始化');
    return;
  }

  if (!window.Auth || !window.Auth.isLoggedIn()) {
    console.error('用户未登录');
    return;
  }

  // 确保DOM元素已初始化
  if (!chatElementsInitialized) {
    console.log('聊天DOM元素未初始化，尝试初始化');
    if (!initChatElements()) {
      console.error('无法初始化聊天DOM元素，放弃连接');
      return;
    }
  }

  try {
    // 连接到Socket.IO服务器
    console.log('连接到Socket.IO服务器');
    socket = io({
      auth: {
        token: window.Auth.getCurrentUser().id // 可以用于服务器端验证
      }
    });

    // 连接事件
    socket.on('connect', () => {
      console.log('已连接到聊天服务器');
      isConnected = true;
      updateConnectionStatus(true);

      // 加入默认聊天室
      joinRoom('public');
    });

    // 断开连接事件
    socket.on('disconnect', () => {
      console.log('与聊天服务器断开连接');
      isConnected = false;
      updateConnectionStatus(false);
    });

    // 连接错误事件
    socket.on('connect_error', (error) => {
      console.error('连接聊天服务器失败:', error.message);
      isConnected = false;
      updateConnectionStatus(false);
      if (chatMessages) {
        window.Utils.safeSetInnerHTML(chatMessages, `<div class="alert alert-danger">连接聊天服务器失败: ${error.message}</div>`);
      }
    });

    // 用户加入事件
    socket.on('user_joined', (data) => {
      console.log('用户加入:', data);

      // 更新用户列表
      onlineUsers = data.users || [];
      updateUsersList();

      // 显示系统消息
      if (data.username !== window.Auth.getCurrentUser().username) {
        appendSystemMessage(`${data.username} 加入了聊天室`);
      }

      // 加载历史消息
      if (data.messages && data.messages.length > 0) {
        if (chatMessages) {
          window.Utils.safeSetInnerHTML(chatMessages, ''); // 清空现有消息
          data.messages.forEach(msg => {
            appendMessage(msg);
          });

          // 滚动到底部
          scrollToBottom();
        }
      }
    });

    // 用户离开事件
    socket.on('user_left', (data) => {
      console.log('用户离开:', data);

      // 更新用户列表
      onlineUsers = onlineUsers.filter(user => user.userId !== data.userId);
      updateUsersList();

      // 显示系统消息
      appendSystemMessage(`${data.username} 离开了聊天室`);
    });

    // 群聊消息事件
    socket.on('group_message', (message) => {
      console.log('收到群聊消息:', message);
      appendMessage(message);
    });

    // 私聊消息事件
    socket.on('private_message', (message) => {
      console.log('收到私聊消息:', message);

      // 如果当前不是与发送者的私聊，则在用户列表中高亮显示
      if (message.from && message.from !== currentPrivateChat) {
        highlightUser(message.from);
      }

      // 如果是当前聊天，则显示消息
      if ((message.from && message.from === currentPrivateChat) ||
        (message.to && message.to === currentPrivateChat)) {
        appendMessage(message);
      }
    });

    // 文件消息事件
    socket.on('file_message', (message) => {
      console.log('收到文件消息:', message);

      // 处理群组文件消息
      if (!message.from && !message.to) {
        appendFileMessage(message);
        return;
      }

      // 处理私人文件消息
      if (message.from && message.from !== currentPrivateChat) {
        highlightUser(message.from);
      }

      if ((message.from && message.from === currentPrivateChat) ||
        (message.to && message.to === currentPrivateChat)) {
        appendFileMessage(message);
      }
    });
  } catch (error) {
    console.error('Socket初始化错误:', error);
    if (chatMessages) {
      window.Utils.safeSetInnerHTML(chatMessages, `<div class="alert alert-danger">初始化聊天失败: ${error.message}</div>`);
    }
  }
}

// 加入聊天室
function joinRoom(roomId) {
  console.log(`加入聊天室: ${roomId}`);
  if (!isConnected || !socket) {
    console.error('未连接到聊天服务器');
    return;
  }

  // 更新当前房间
  currentRoom = roomId;
  currentPrivateChat = null;

  // 更新UI
  updateRoomsList();
  if (currentChatTitle) {
    // 根据房间ID显示友好的名称
    const roomName = roomId === 'public' ? '公共聊天室' : roomId;
    currentChatTitle.textContent = roomName;
  }
  if (chatMessages) {
    chatMessages.innerHTML = ''; // 清空聊天记录
  }

  // 通知服务器
  socket.emit('user_join', {
    username: window.Auth.getCurrentUser().username,
    userId: window.Auth.getCurrentUser().id,
    room: roomId
  });
}

// 开始私聊
function startPrivateChat(userId, username) {
  console.log(`开始私聊: ${username} (${userId})`);
  if (!isConnected || !socket) {
    console.error('未连接到聊天服务器');
    return;
  }

  // 更新当前聊天状态
  currentRoom = null;
  currentPrivateChat = userId;

  // 更新UI
  updateRoomsList();
  updateUsersList();
  if (currentChatTitle) {
    currentChatTitle.textContent = `与 ${username} 私聊`;
  }
  if (chatMessages) {
    chatMessages.innerHTML = ''; // 清空聊天记录
    chatMessages.innerHTML = '<div class="text-center text-muted my-2">开始私聊会话</div>';
  }

  // 可以向服务器请求历史私聊消息
  // ...
}

// 创建新房间
async function createRoom(roomName, description, password = null, isPrivate = false) {
  try {
    const response = await fetch('/api/rooms', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: roomName,
        description: description || '',
        password: password || null,
        isPrivate: isPrivate || false
      }),
      credentials: 'include',
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || '创建房间失败');
    }

    // 隐藏模态框，重置表单
    if (createRoomModal) {
      createRoomModal.hide();
    }
    if (createRoomForm) {
      createRoomForm.reset();
    }

    // 自动加入新创建的房间
    joinRoom(data.id);

    // 更新房间列表
    updateRoomsList();

    return data;
  } catch (error) {
    console.error('创建房间错误:', error);
    if (roomError) {
      roomError.textContent = error.message;
      roomError.classList.remove('d-none');
    }
    throw error;
  }
}

// 加入房间
async function joinRoom(roomId, password = null) {
  try {
    if (password) {
      const response = await fetch(`/api/rooms/${roomId}/join`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ password: password }),
        credentials: 'include',
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '加入房间失败');
      }
    }

    // 切换到新房间
    currentRoom = roomId;
    currentPrivateChat = null;

    // 更新UI
    updateCurrentChatTitle();

    // 通知Socket.IO服务器
    if (socket && isConnected) {
      const currentUser = window.Auth.getCurrentUser();
      socket.emit('user_join', {
        username: currentUser.username,
        userId: currentUser.id,
        room: roomId
      });
    }

    // 清空消息区域
    if (chatMessages) {
      chatMessages.innerHTML = '';
    }

    // 更新房间列表的活动状态
    updateRoomsListActiveState();

    return true;
  } catch (error) {
    console.error('加入房间错误:', error);
    alert(error.message);
    return false;
  }
}

// 离开房间
async function leaveRoom(roomId) {
  try {
    const response = await fetch(`/api/rooms/${roomId}/leave`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || '离开房间失败');
    }

    // 如果是当前房间，切换到公共房间
    if (currentRoom === roomId) {
      joinRoom('public');
    }

    // 更新房间列表
    updateRoomsList();

    return true;
  } catch (error) {
    console.error('离开房间错误:', error);
    alert(error.message);
    return false;
  }
}

// 删除房间
async function deleteRoom(roomId) {
  if (!confirm('确定要删除这个房间吗？此操作不可撤销。')) {
    return false;
  }

  try {
    const response = await fetch(`/api/rooms/${roomId}`, {
      method: 'DELETE',
      credentials: 'include',
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || '删除房间失败');
    }

    // 如果是当前房间，切换到公共房间
    if (currentRoom === roomId) {
      joinRoom('public');
    }

    // 更新房间列表
    updateRoomsList();

    return true;
  } catch (error) {
    console.error('删除房间错误:', error);
    alert(error.message);
    return false;
  }
}

// 发送消息
function sendMessage() {
  console.log('尝试发送消息');
  if (!isConnected || !socket) {
    console.error('未连接到聊天服务器');
    alert('未连接到聊天服务器，请重新加载页面');
    return;
  }

  if (!messageInput) {
    console.error('找不到消息输入框元素');
    return;
  }

  const message = messageInput.value.trim();
  if (!message) return;

  try {
    if (currentRoom) {
      // 发送群聊消息
      console.log(`发送群聊消息到 ${currentRoom}: ${message}`);
      socket.emit('group_message', {
        message,
        room: currentRoom
      });
    } else if (currentPrivateChat) {
      // 发送私聊消息
      console.log(`发送私聊消息到 ${currentPrivateChat}: ${message}`);
      socket.emit('private_message', {
        to: currentPrivateChat,
        message
      });
    }

    // 清空输入框
    messageInput.value = '';
  } catch (error) {
    console.error('发送消息错误:', error);
    alert('发送消息失败: ' + error.message);
  }
}

// 发送文件
function sendFile() {
  console.log('尝试发送文件');
  if (!isConnected || !socket) {
    console.error('未连接到聊天服务器');
    alert('未连接到聊天服务器，请重新加载页面');
    return;
  }

  if (!fileInput || !fileInput.files.length) {
    console.error('没有选择文件');
    return;
  }

  const file = fileInput.files[0];
  const formData = new FormData();
  formData.append('file', file);

  // 上传文件到服务器
  fetch('/api/files/upload', {
    method: 'POST',
    body: formData,
    credentials: 'include',
  })
    .then(response => response.json())
    .then(fileData => {
      // 发送文件消息
      if (currentRoom) {
        // 发送群组文件消息
        console.log(`发送群组文件消息到 ${currentRoom}: ${fileData.originalName}`);
        socket.emit('file_message', {
          to: currentRoom,
          fileId: fileData.id,
          fileName: fileData.originalName,
          fileType: file.type,
          isGroup: true
        });
      } else if (currentPrivateChat) {
        // 发送私人文件消息
        console.log(`发送私人文件消息到 ${currentPrivateChat}: ${fileData.originalName}`);
        socket.emit('file_message', {
          to: currentPrivateChat,
          fileId: fileData.id,
          fileName: fileData.originalName,
          fileType: file.type,
          isGroup: false
        });
      }

      // 清空文件输入
      fileInput.value = '';
    })
    .catch(error => {
      console.error('文件上传错误:', error);
      alert('文件上传失败: ' + error.message);
    });
}

// 追加消息到聊天区域
function appendMessage(message) {
  if (!chatMessages) {
    console.error('找不到聊天消息区域元素');
    return;
  }

  const messageElement = document.createElement('div');
  messageElement.className = 'message';

  // 判断是否为自己发送的消息
  const isSelf = message.userId === window.Auth.getCurrentUser().id;
  if (isSelf) {
    messageElement.classList.add('outgoing');
  } else {
    messageElement.classList.add('incoming');
  }

  // 消息内容
  messageElement.innerHTML = `
    <div class="sender">${isSelf ? '我' : message.username}</div>
    <div class="content">${window.Utils.escapeHTML(message.message || '')}</div>
    <div class="time">${window.Utils.formatTime(message.timestamp)}</div>
  `;

  chatMessages.appendChild(messageElement);
  scrollToBottom();
}

// 追加文件消息
function appendFileMessage(message) {
  if (!chatMessages) {
    console.error('找不到聊天消息区域元素');
    return;
  }

  const messageElement = document.createElement('div');
  messageElement.className = 'message file-message';

  // 判断是否为自己发送的消息
  const isSelf = message.userId === window.Auth.getCurrentUser().id;
  if (isSelf) {
    messageElement.classList.add('outgoing');
  } else {
    messageElement.classList.add('incoming');
  }

  // 获取文件图标
  const fileIcon = getFileIcon(message.fileType);

  // 消息内容
  messageElement.innerHTML = `
    <div class="sender">${isSelf ? '我' : message.username}</div>
    <div class="content">
      <a href="/api/files/${message.fileId}" target="_blank" download>
        <span class="file-icon">${fileIcon}</span>
        ${window.Utils.escapeHTML(message.fileName || '未命名文件')}
      </a>
    </div>
    <div class="time">${window.Utils.formatTime(message.timestamp)}</div>
  `;

  chatMessages.appendChild(messageElement);
  scrollToBottom();
}

// 追加系统消息
function appendSystemMessage(text) {
  if (!chatMessages) {
    console.error('找不到聊天消息区域');
    return;
  }

  const messageElement = document.createElement('div');
  messageElement.className = 'text-center text-muted my-2';
  messageElement.textContent = text;

  chatMessages.appendChild(messageElement);
  scrollToBottom();
}

// 更新用户列表
function updateUsersList() {
  if (!usersList) {
    console.error('找不到用户列表元素');
    return;
  }

  usersList.innerHTML = '';

  if (!onlineUsers || onlineUsers.length === 0) {
    usersList.innerHTML = '<div class="text-center text-muted p-3">暂无在线用户</div>';
    return;
  }

  // 排序用户列表：在线用户优先，然后按用户名排序
  const sortedUsers = [...onlineUsers].sort((a, b) => a.username.localeCompare(b.username));

  sortedUsers.forEach(user => {
    if (user.userId === window.Auth.getCurrentUser().id) return; // 不显示自己

    const userElement = document.createElement('button');
    userElement.className = 'list-group-item list-group-item-action';

    // 如果是当前私聊用户，则高亮显示
    if (currentPrivateChat && user.userId === currentPrivateChat) {
      userElement.classList.add('active');
    }

    userElement.dataset.userId = user.userId;
    userElement.innerHTML = `
      <div class="d-flex align-items-center">
        <div class="user-status online me-2"></div>
        ${window.Utils.escapeHTML(user.username)}
      </div>
    `;

    // 点击用户开始私聊
    userElement.addEventListener('click', () => {
      startPrivateChat(user.userId, user.username);
    });

    usersList.appendChild(userElement);
  });
}

// 更新房间列表
async function updateRoomsList() {
  if (!roomsList) {
    console.error('找不到房间列表元素');
    return;
  }

  try {
    // 从服务器获取房间列表
    const response = await fetch('/api/rooms');
    const rooms = await response.json();

    // 清空现有房间列表
    roomsList.innerHTML = '';

    // 首先添加公共聊天室
    const publicRoomBtn = document.createElement('button');
    publicRoomBtn.className = `list-group-item list-group-item-action ${currentRoom === 'public' ? 'active' : ''}`;
    publicRoomBtn.dataset.room = 'public';
    publicRoomBtn.innerHTML = `
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <strong>公共聊天室</strong>
          <br><small class="text-muted">所有用户都可以参与的公共聊天室</small>
        </div>
      </div>
    `;

    publicRoomBtn.addEventListener('click', () => {
      joinRoom('public');
    });

    roomsList.appendChild(publicRoomBtn);

    // 添加其他房间
    rooms.forEach(room => {
      const roomBtn = document.createElement('button');
      roomBtn.className = `list-group-item list-group-item-action ${room.id === currentRoom ? 'active' : ''}`;
      roomBtn.dataset.room = room.id;

      const lockIcon = room.isPrivate ? '<i class="bi bi-lock-fill"></i> ' : '';
      const deleteBtn = getCurrentUserId() === room.creator_id ? `
        <button class="btn btn-sm btn-outline-danger ms-2 delete-room-btn" 
                data-room-id="${room.id}" 
                onclick="event.stopPropagation(); deleteRoom('${room.id}')">
          <i class="bi bi-trash"></i>
        </button>
      ` : '';

      roomBtn.innerHTML = `
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <strong>${lockIcon}${room.name}</strong>
            ${room.description ? `<br><small class="text-muted">${room.description}</small>` : ''}
          </div>
          <div class="d-flex align-items-center">
            ${deleteBtn}
          </div>
        </div>
      `;

      roomBtn.addEventListener('click', () => {
        if (room.isPrivate) {
          // 私有房间使用模态框输入密码
          currentRoomForJoin = room.id;
          if (joinRoomModal) {
            // 清空之前的错误和密码
            const joinRoomError = document.getElementById('join-room-error');
            const joinRoomPasswordInput = document.getElementById('join-room-password-input');
            if (joinRoomError) {
              joinRoomError.classList.add('d-none');
            }
            if (joinRoomPasswordInput) {
              joinRoomPasswordInput.value = '';
            }
            joinRoomModal.show();
          } else {
            // 备用方案：使用prompt
            const password = prompt('请输入房间密码：');
            if (password) {
              joinRoom(room.id, password);
            }
          }
        } else {
          joinRoom(room.id);
        }
      });

      roomsList.appendChild(roomBtn);
    });

  } catch (error) {
    console.error('获取房间列表失败:', error);

    // 如果获取失败，至少显示公共聊天室
    roomsList.innerHTML = '';
    const publicRoomBtn = document.createElement('button');
    publicRoomBtn.className = `list-group-item list-group-item-action ${currentRoom === 'public' ? 'active' : ''}`;
    publicRoomBtn.dataset.room = 'public';
    publicRoomBtn.textContent = '公共聊天室';

    publicRoomBtn.addEventListener('click', () => {
      joinRoom('public');
    });

    roomsList.appendChild(publicRoomBtn);
  }
}

// 获取房间名称
function getRoomName(roomId) {
  if (roomId === 'public') {
    return '公共聊天室';
  }

  // 从房间列表中查找房间名称
  const roomBtn = roomsList.querySelector(`[data-room="${roomId}"]`);
  if (roomBtn) {
    const strongElement = roomBtn.querySelector('strong');
    if (strongElement) {
      return strongElement.textContent.replace(/🔒\s*/, ''); // 移除锁定图标
    }
  }

  return roomId; // 回退到房间ID
}

// 更新当前聊天标题
function updateCurrentChatTitle() {
  if (!currentChatTitle) {
    return;
  }

  if (currentRoom) {
    // 房间聊天
    const roomName = getRoomName(currentRoom);
    currentChatTitle.textContent = roomName;
  } else if (currentPrivateChat) {
    // 私聊
    const targetUser = onlineUsers.find(user => user.userId === currentPrivateChat);
    const username = targetUser ? targetUser.username : '未知用户';
    currentChatTitle.textContent = `与 ${username} 私聊`;
  } else {
    currentChatTitle.textContent = '聊天室';
  }
}

// 获取当前用户ID
function getCurrentUserId() {
  const user = window.Auth.getCurrentUser();
  return user ? user.id : null;
}

// 更新房间列表的活动状态
function updateRoomsListActiveState() {
  if (!roomsList) {
    return;
  }

  // 移除所有活动状态
  const roomButtons = roomsList.querySelectorAll('.list-group-item');
  roomButtons.forEach(btn => {
    btn.classList.remove('active');
  });

  // 添加当前房间的活动状态
  const currentRoomBtn = roomsList.querySelector(`[data-room="${currentRoom}"]`);
  if (currentRoomBtn) {
    currentRoomBtn.classList.add('active');
  }
}

// 高亮显示用户（有新消息时）
function highlightUser(userId) {
  if (!usersList) {
    console.error('找不到用户列表元素');
    return;
  }

  const userElement = usersList.querySelector(`[data-user-id="${userId}"]`);
  if (userElement) {
    userElement.classList.add('bg-light');
    // 添加闪烁效果
    userElement.style.animation = 'blink 1s 3';
    setTimeout(() => {
      userElement.style.animation = '';
    }, 3000);
  }
}

// 更新连接状态
function updateConnectionStatus(connected) {
  if (!chatStatus) {
    console.error('找不到聊天状态元素');
    return;
  }

  if (connected) {
    chatStatus.textContent = '在线';
    chatStatus.className = 'badge bg-success';
  } else {
    chatStatus.textContent = '离线';
    chatStatus.className = 'badge bg-danger';
  }
}

// 根据文件类型获取图标
function getFileIcon(fileType) {
  if (!fileType) return '📄';

  if (fileType.startsWith('image/')) {
    return '🖼️';
  } else if (fileType.startsWith('audio/')) {
    return '🔊';
  } else if (fileType.startsWith('video/')) {
    return '🎬';
  } else if (fileType.startsWith('text/')) {
    return '📝';
  } else if (fileType.includes('pdf')) {
    return '📑';
  } else if (fileType.includes('word') || fileType.includes('document')) {
    return '📃';
  } else if (fileType.includes('excel') || fileType.includes('spreadsheet')) {
    return '📊';
  } else if (fileType.includes('powerpoint') || fileType.includes('presentation')) {
    return '📊';
  } else if (fileType.includes('zip') || fileType.includes('compressed')) {
    return '🗜️';
  }

  return '📄';
}

// 滚动到聊天区域底部
function scrollToBottom() {
  if (!chatMessages) {
    console.error('找不到聊天消息区域元素');
    return;
  }

  chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 设置事件监听
function setupEventListeners() {
  console.log('设置聊天事件监听');

  // 确保DOM元素已初始化
  if (!chatElementsInitialized) {
    console.log('聊天DOM元素未初始化，不设置事件监听');
    return;
  }

  if (sendMessageBtn) {
    sendMessageBtn.addEventListener('click', () => {
      console.log('点击发送消息按钮');
      sendMessage();
    });
  } else {
    console.error('找不到发送消息按钮');
  }

  if (messageInput) {
    messageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });
  } else {
    console.error('找不到消息输入框');
  }

  if (sendFileBtn) {
    sendFileBtn.addEventListener('click', () => {
      console.log('点击发送文件按钮');
      if (!window.Auth || !window.Auth.isLoggedIn()) {
        alert('请先登录');
        return;
      }

      if (fileInput) {
        fileInput.click();
      } else {
        console.error('找不到文件输入元素');
      }
    });
  } else {
    console.error('找不到发送文件按钮');
  }

  if (fileInput) {
    fileInput.addEventListener('change', () => {
      console.log('选择文件:', fileInput.files[0]?.name);
      sendFile();
    });
  } else {
    console.error('找不到文件输入元素');
  }

  // 设置创建房间按钮事件
  if (createRoomBtn) {
    createRoomBtn.addEventListener('click', () => {
      console.log('点击创建房间按钮');
      if (!window.Auth || !window.Auth.isLoggedIn()) {
        alert('请先登录');
        return;
      }

      if (roomError) {
        roomError.classList.add('d-none');
      }

      if (createRoomModal) {
        createRoomModal.show();
      }
    });
  }

  // 设置创建房间表单提交事件
  if (createRoomForm) {
    createRoomForm.addEventListener('submit', async (e) => {
      e.preventDefault();

      const roomName = document.getElementById('room-name-input').value.trim();
      const description = document.getElementById('room-description-input').value.trim();
      const password = document.getElementById('room-password-input').value.trim();
      const isPrivate = document.getElementById('room-private-checkbox').checked;

      if (roomError) {
        roomError.classList.add('d-none');
      }

      if (!roomName) {
        if (roomError) {
          roomError.textContent = '房间名称不能为空';
          roomError.classList.remove('d-none');
        }
        return;
      }

      if (isPrivate && !password) {
        if (roomError) {
          roomError.textContent = '私有房间必须设置密码';
          roomError.classList.remove('d-none');
        }
        return;
      }

      try {
        await createRoom(roomName, description, password, isPrivate);
      } catch (error) {
        // 错误已在createRoom中处理
      }
    });
  }

  // 设置加入房间表单提交事件
  if (joinRoomForm) {
    joinRoomForm.addEventListener('submit', async (e) => {
      e.preventDefault();

      const password = document.getElementById('join-room-password-input').value.trim();
      const joinRoomError = document.getElementById('join-room-error');

      if (joinRoomError) {
        joinRoomError.classList.add('d-none');
      }

      if (!password) {
        if (joinRoomError) {
          joinRoomError.textContent = '请输入房间密码';
          joinRoomError.classList.remove('d-none');
        }
        return;
      }

      if (!currentRoomForJoin) {
        if (joinRoomError) {
          joinRoomError.textContent = '房间信息错误，请重试';
          joinRoomError.classList.remove('d-none');
        }
        return;
      }

      try {
        const success = await joinRoom(currentRoomForJoin, password);
        if (success) {
          // 成功加入房间，关闭模态框
          if (joinRoomModal) {
            joinRoomModal.hide();
          }
          currentRoomForJoin = null;
        }
      } catch (error) {
        if (joinRoomError) {
          joinRoomError.textContent = error.message;
          joinRoomError.classList.remove('d-none');
        }
      }
    });
  }

  // 设置私有房间复选框事件
  const privateCheckbox = document.getElementById('room-private-checkbox');
  const passwordSection = document.getElementById('room-password-section');

  if (privateCheckbox && passwordSection) {
    privateCheckbox.addEventListener('change', () => {
      if (privateCheckbox.checked) {
        passwordSection.classList.remove('d-none');
      } else {
        passwordSection.classList.add('d-none');
        // 清空密码字段
        const passwordInput = document.getElementById('room-password-input');
        if (passwordInput) {
          passwordInput.value = '';
        }
      }
    });
  }
}

// 初始化聊天模块
function initChat() {
  console.log('初始化聊天模块');

  try {
    // 不立即初始化元素，等待页面切换事件

    // 聊天页面显示时初始化Socket
    document.addEventListener('pageChanged', (e) => {
      console.log('页面改变事件:', e.detail);
      if (e.detail.page === 'chat') {
        console.log('显示聊天页面，准备初始化');

        // 使用延迟确保DOM已完全渲染
        setTimeout(() => {
          console.log('开始初始化聊天元素');
          if (initChatElements()) {
            console.log('聊天元素初始化成功，设置事件监听');
            setupEventListeners();

            if (window.Auth && window.Auth.isLoggedIn && window.Auth.isLoggedIn()) {
              console.log('用户已登录，初始化Socket');
              initializeSocket();
              updateRoomsList();
            } else {
              console.log('用户未登录，显示登录提示');
              if (chatMessages) {
                window.Utils.safeSetInnerHTML(chatMessages, '<div class="alert alert-warning">请先登录后使用聊天功能</div>');
              }
            }
          } else {
            console.error('聊天元素初始化失败');
            // 尝试在页面上显示错误
            const chatPage = document.getElementById('chat-page');
            if (chatPage) {
              chatPage.innerHTML = '<div class="alert alert-danger">加载聊天功能失败: 无法初始化必要组件</div>';
            }
          }
        }, 300);
      }
    });

    // 登录后初始化Socket
    document.addEventListener('userLoggedIn', () => {
      console.log('用户登录事件');
      if (window.Auth && window.Auth.isLoggedIn()) {
        console.log('用户已登录:', window.Auth.getCurrentUser().username);
        if (document.querySelector('#chat-page:not(.d-none)')) {
          console.log('聊天页面可见，初始化Socket');

          // 确保元素已初始化
          if (!chatElementsInitialized) {
            if (!initChatElements()) {
              console.error('无法初始化聊天DOM元素');
              return;
            }
            setupEventListeners();
          }

          initializeSocket();
        }
      }
    });

    // 登出时断开Socket连接
    document.addEventListener('userLoggedOut', () => {
      console.log('用户登出事件');
      if (socket) {
        console.log('断开Socket连接');
        socket.disconnect();
        socket = null;
        isConnected = false;
        updateConnectionStatus(false);
      }
    });

    console.log('聊天模块初始化完成');
  } catch (err) {
    console.error('初始化聊天模块错误:', err);
  }
}

// 当DOM加载完成后初始化聊天模块
document.addEventListener('DOMContentLoaded', () => {
  // 确保Bootstrap完全加载
  setTimeout(initChat, 600);
});

// 添加CSS动画
const style = document.createElement('style');
style.innerHTML = `
@keyframes blink {
  0% { background-color: inherit; }
  50% { background-color: #e9ecef; }
  100% { background-color: inherit; }
}
`;
document.head.appendChild(style);

// 导出函数
window.Chat = {
  initializeSocket,
  joinRoom,
  startPrivateChat,
  sendMessage,
  sendFile
};